<template>
	<div class="login-wrapper">
		<div class="login-content">
			<div class="login-main">
				<h2 class="login-main-title">{{ language.title }}</h2>
				<el-tabs v-model="loginType" @tab-click="handleTabClick">
					<el-tab-pane label="账号密码登录" name="account">
						<el-form :model="accountForm" :rules="accountRules" ref="accountForm"
							@keyup.enter.native="handleAccountLogin">
							<el-form-item prop="name">
								<el-input v-model="accountForm.name" placeholder="用户名"></el-input>
							</el-form-item>
							<el-form-item prop="password">
								<el-input v-model="accountForm.password" type="password"
									:placeholder="language.password"></el-input>
							</el-form-item>
							<el-form-item style="text-align: center;">
								<el-button class="login-btn-submit" type="primary" @click="handleAccountLogin"
									style="width: 100%;">登录</el-button>
							</el-form-item>
						</el-form>
					</el-tab-pane>
					<el-tab-pane label="邮箱验证码登录" name="email">
						<el-form :model="emailForm" :rules="emailRules" ref="emailForm"
							@keyup.enter.native="handleEmailLogin">
							<el-form-item prop="email">
								<el-input v-model="emailForm.email" placeholder="请输入邮箱">
									<template slot="append">
										<el-button :disabled="timer > 0" @click="sendCode" class="send-code-btn">
											{{ timer > 0 ? `${countdown}s后重试` : '获取验证码' }}
										</el-button>
									</template>
								</el-input>
							</el-form-item>
							<el-form-item prop="code">
								<el-input v-model="emailForm.code" placeholder="请输入验证码"></el-input>
							</el-form-item>
							<el-form-item style="text-align: center;">
								<el-button class="login-btn-submit" type="primary" @click="handleEmailLogin"
									style="width: 100%;">登录</el-button>
							</el-form-item>
						</el-form>
					</el-tab-pane> 
				</el-tabs>
				<div style="text-align: center; margin-top: 20px;">
					<el-button type="text" @click="$router.push({ name: 'Register' })">还没有账号？去注册</el-button>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
import {
	mapActions,
	mapMutations
} from 'vuex'
import {
	setToken,
	loginByNamePwd,
	loginByEmailCode,
	sendEmailCode,
	getUserRole
} from '@/http/modules/admin'
export default {
	data() {
		return {
			loginType: 'account',
			accountForm: {
				name: '',
				password: ''
			},
			emailForm: {
				email: '',
				code: ''
			},
			timer: null,
			countdown: 0,
			accountRules: {
				name: [{
					required: true,
					message: '请输入用户名',
					trigger: 'blur'
				}],
				password: [{
					required: true,
					message: '请输入密码',
					trigger: 'blur'
				}]
			},
			emailRules: {
				email: [{
					required: true,
					message: '请输入邮箱',
					trigger: 'blur'
				}, {
					type: 'email',
					message: '请输入正确的邮箱格式',
					trigger: 'blur'
				}],
				code: [{
					required: true,
					message: '请输入验证码',
					trigger: 'blur'
				}]
			}
		}
	},
	computed: {
		language() {
			return {
				title: this.$t("login.title"),
				name: this.$t("login.name"),
				password: this.$t("login.password"),
				signIn: this.$t("login.signIn")
			}
		}
	},
	created() {
		localStorage.removeItem("store")
	},
	methods: {
		...mapMutations('user', ['updateName', 'updateRole']),
		handleTabClick() {
			this.$refs[this.loginType + 'Form'].resetFields()
		},
		// 发送验证码
		async sendCode() {
			try {
				// 先验证邮箱是否有效
				await this.$refs.emailForm.validateField('email')
				if (!this.emailForm.email) {
					this.$message.warning('请先输入邮箱')
					return
				}
				console.log('发送验证码，邮箱：', this.emailForm.email)
				const res = await sendEmailCode(this.emailForm.email)
				if (res.data.code === 200) {
					this.$message.success('验证码发送成功')
					this.countdown = 60
					this.timer = setInterval(() => {
						if (this.countdown > 0) {
							this.countdown--
						} else {
							clearInterval(this.timer)
							this.timer = null
						}
					}, 1000)
				} else {
					this.$message.error(res.data.message || '验证码发送失败')
				}
			} catch (error) {
				console.error('发送验证码错误：', error)
				this.$message.error(error.message || '验证码发送失败')
			}
		},
		// 账号密码登录
		async handleAccountLogin() {
			try {
				await this.$refs.accountForm.validate()
				const loginRes = await loginByNamePwd(this.accountForm)
				if (loginRes.data.code === 200) {
					setToken(loginRes.data.data)
					this.updateName(this.accountForm.name)
					
					// 获取用户角色
					const roleRes = await getUserRole()
					if (roleRes.data.code === 200) {
						// 直接使用后端返回的角色名称
						this.updateRole(roleRes.data.data)
						
						// 根据角色跳转到不同的页面
						if (roleRes.data.data === '生产方') {
							this.$router.push('/supplier')
						} else if (roleRes.data.data === '加工方') {
							this.$router.push('/processor')
						} else {
							this.$router.push('/Home/Page')
						}
					}
					
					this.$message.success('登录成功')
				} else {
					this.$message.error(loginRes.data.data || '登录失败')
				}
			} catch (error) {
				console.error('登录失败:', error)
				this.$message.error('登录失败')
			}
		},
		// 邮箱验证码登录
		async handleEmailLogin() {
			try {
				await this.$refs.emailForm.validate()
				const loginRes = await loginByEmailCode(this.emailForm)
				if (loginRes.data.code === 200) {
					setToken(loginRes.data.data)
					this.updateName(loginRes.data.data.userName)
					
					// 获取用户角色
					const roleRes = await getUserRole()
					if (roleRes.data.code === 200) {
						// 直接使用后端返回的角色名称
						this.updateRole(roleRes.data.data)
						
						// 根据角色跳转到不同的页面
						if (roleRes.data.data === '生产方') {
							this.$router.push('/supplier')
						} else if (roleRes.data.data === '加工方') {
							this.$router.push('/processor')
						} else {
							this.$router.push('/Home/Page')
						}
					}
					
					this.$message.success('登录成功')
				} else {
					this.$message.error(loginRes.data.message || '登录失败')
				}
			} catch (error) {
				console.error('登录失败:', error)
				this.$message.error('登录失败')
			}
		}
	},
	beforeDestroy() {
		if (this.timer) {
			clearInterval(this.timer)
		}
	}
}
</script>
<style scoped>
.login-wrapper {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	overflow: hidden;
	background: linear-gradient(135deg, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.3)), url(~@/assets/login_bg.jpg) no-repeat;
	background-size: cover;
	display: flex;
	justify-content: center;
	align-items: center;

	&::before {
		content: '';
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background: radial-gradient(circle at center, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.5) 100%);
		z-index: 1;
	}
}

.login-content {
	position: relative;
	z-index: 2;
	width: 400px;
	padding: 40px;
	background: rgba(255, 255, 255, 0.98);
	backdrop-filter: blur(10px);
	border-radius: 15px;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3),
		inset 0 0 0 1px rgba(255, 255, 255, 0.1);
	animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(-20px);
	}

	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.login-main {
	color: #ffffff;
}

.login-main-title {
	text-align: center;
	margin-bottom: 30px;
	font-size: 24px;
	font-weight: 500;
	letter-spacing: 1px;
	color: #0f172a;
	text-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.el-form-item {
	margin-bottom: 25px;
}

.login-wrapper ::v-deep .el-input__inner {
	height: 45px;
	line-height: 45px;
	background-color: rgba(255, 255, 255, 0.05);
	border: 2px solid #cbd5e0;
	border-radius: 8px;
	color: #2d3748;
	font-size: 14px;
	transition: all 0.3s ease;
}

.login-wrapper ::v-deep .el-input__inner:hover,
.login-wrapper ::v-deep .el-input__inner:focus {
	border-color: #409EFF;
	background-color: rgba(255, 255, 255, 0.1);
}

.login-wrapper ::v-deep .el-input__inner::placeholder {
	color: #94a3b8;
}

.el-button {
	height: 45px;
	border-radius: 8px;
	font-size: 14px;
	letter-spacing: 1px;
	transition: all 0.3s ease;
}

.el-button--primary {
	background: linear-gradient(135deg, #4f46e5, #6366f1);
	border: none;
	box-shadow: 0 4px 15px rgba(79,70,229,0.3);
	color: white !important;
	text-shadow: 0 1px 2px rgba(0,0,0,0.1);
	position: relative;
	overflow: hidden;
}

.el-button--primary::after {
	content: '';
	position: absolute;
	top: 0;
	left: -100%;
	width: 200%;
	height: 100%;
	background: linear-gradient(
		90deg,
		rgba(255,255,255,0) 0%,
		rgba(255,255,255,0.15) 50%,
		rgba(255,255,255,0) 100%
	);
	animation: shine 1.5s infinite;
}

@keyframes shine {
	100% {
		left: 100%;
	}
}

.el-button--primary:hover {
	transform: translateY(-2px);
	box-shadow: 0 6px 20px rgba(79,70,229,0.3);
}

.el-button--primary.is-plain {
	background: transparent;
	border: 1px solid rgba(64, 158, 255, 0.5);
	color: #409EFF;
}

.el-button--primary.is-plain:hover {
	color: #fff;
	background: linear-gradient(135deg, #409EFF, #3a8ee6);
	border-color: transparent;
	transform: translateY(-1px);
	box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

.login-select {
	width: 120px;
}

/* 添加标签页样式 */
.login-wrapper ::v-deep .el-tabs__item {
	color: #334155 !important;
	font-size: 16px;
	font-weight: 500;
}

.login-wrapper ::v-deep .el-tabs__item.is-active {
	color: #409EFF !important;
	font-weight: 600;
}

.login-wrapper ::v-deep .el-tabs__active-bar {
	height: 4px;
	background: #4f46e5;
	border-radius: 2px;
}

.el-tabs__nav-wrap::after {
	background-color: rgba(255, 255, 255, 0.1);
}

/* 发送验证码按钮样式 */
.send-code-btn {
	margin: 0;
	height: 100%;
	padding: 0 15px;
	border: none;
	background: transparent;
	color: #409EFF;
	font-size: 14px;
	cursor: pointer;
	transition: all 0.3s;
	white-space: nowrap;
	min-width: 100px;
}

.send-code-btn:hover:not(:disabled) {
	color: #66b1ff;
}

.send-code-btn:disabled {
	color: #909399;
	cursor: not-allowed;
}

/* 确保输入框附加按钮样式正确 */
.el-input-group__append {
	background: transparent;
	border-color: rgba(64, 158, 255, 0.3);
	padding: 0;
	width: auto;
}

.el-input-group__append:hover {
	border-color: #409EFF;
}

/* 调整邮箱输入框样式 */
.el-input-group--append .el-input__inner {
	padding-right: 110px;
}

/* 优化输入框聚焦状态 */
.el-input.is-active .el-input__inner {
	border-color: #4f46e5;
	box-shadow: 0 0 0 3px rgba(79,70,229,0.2);
}

/* 优化去注册按钮 */
.el-button--text {
	color: #4f46e5;
	font-weight: 500;
	transition: all 0.3s ease;
	position: relative;
	padding: 8px 16px;
	border-radius: 8px;
}

.el-button--text:hover {
	color: #4f46e5 !important;
	transform: translateY(-1px);
	background: rgba(79,70,229,0.05);
}

.el-button--text::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 0;
	width: 0;
	height: 2px;
	background: #4f46e5;
	transition: width 0.3s ease;
}

.el-button--text:hover::after {
	width: 100%;
}
</style>
